import java.util.PriorityQueue;
import java.util.TimerTask;

//创建一个类,来描述任务（至少包含任务内容和执行时间）
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;
    public Runnable getRunnable() {
        return this.runnable;
    }
    public long getTime() {
        return this.time;
    }
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }


}

class MyTimer {
    //锁对象
    private Object locker = new Object();
    //使用优先级队列需要指定比较标准
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimerTask(runnable, delay));
            locker.notify();
        }
    }
    public MyTimer() {
        //扫描线程，如果没到执行时间，则反复不停地扫描
        Thread t = new Thread(() -> {
            while(true) {
                try{
                    synchronized (locker) {
                        //判断队列是否为空
                        while(queue.isEmpty()) {
                            //如果为空则等待新任务的添加将其唤醒
                            locker.wait();
                        }
                        //不为空，此时就需要进行判断是否到执行时间
                        //获取当时优先级队列中的首要任务（最小时间）
                        MyTimerTask task = queue.peek();
                        //获取当前系统的时间
                        long curTime = System.currentTimeMillis();
                        if(task.getTime() <= curTime) {
                            task.getRunnable().run();
                            //执行完毕，删除当前的任务
                            queue.poll();
                        }else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class test2 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        System.out.println("程序启动！！");

    }
}
